const { Op } = require('sequelize');

const { getPagination } = require('@utils/tools');

const goods = require('./goods.model');

module.exports = {
  async goodsAdd({ goods_name, goods_num, goods_price, goods_img }) {
    const res = await goods.create({
      goods_name,
      goods_num,
      goods_price,
      goods_img,
    });

    return res.dataValues;
  },

  async goodsRemove({ id }) {
    try {
      const res = await goods.destroy({
        where: { id },
      });

      return res > 0;
    } catch (error) {
      console.log(`\x1B[45m ${error} \x1B[0m`);
    }
  },

  async goodsRestore({ id }) {
    try {
      const res = await goods.restore({
        where: { id },
      });

      return res > 0;
    } catch (error) {
      console.log(`\x1B[45m ${error} \x1B[0m`);
    }
  },

  async goodsUpdate(body) {
    const { id, ...args } = body;

    try {
      const [bool] = await goods.update(args, {
        where: {
          id,
        },
      });

      return bool > 0;
    } catch (error) {
      console.log(`\x1B[45m ${error} \x1B[0m`);
    }
  },

  async goodsGetList(query) {
    const { page_size = 10, page_num = 1, ...whereOpt } = query;

    const { offset, limit } = getPagination(page_num, page_size);

    try {
      const where = {};
      const name = whereOpt.goods_name;
      if (name) {
        where.goods_name = {
          [Op.like]: `%${name}%`,
        };
      }
      const { count, rows } = await goods.findAndCountAll({
        where,
        offset,
        limit,
      });

      return { rows, count, page_size, page_num };
    } catch (error) {
      console.log(`\x1B[45m ${error} \x1B[0m`);
    }
  },
};
